<template>
  <div class="login-account">
    <el-form ref="loginFormRef" :model="loginForm" :rules="loginRules" label-width="60px">
      <el-form-item prop="name" label="账号">
        <el-input v-model="loginForm.name" />
      </el-form-item>
      <el-form-item prop="password" label="密码">
        <el-input v-model="loginForm.password" show-password />
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts">
import { defineComponent, reactive, ref } from 'vue'
import { useStore } from 'vuex'
import type { FormInstance } from 'element-plus'
import setStorage from '@/utils/setCatch'

export default defineComponent({
  setup() {
    const store = useStore()
    const loginForm = reactive({
      name: setStorage.getCatch('name') ?? '',
      password: setStorage.getCatch('password') ?? ''
    })
    const loginRules = {
      name: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { pattern: /^[a-z0-9]{5,10}$/, message: '用户名必须是5-10个字母或数字', trigger: 'blur' }
      ],
      password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { pattern: /^[a-z0-9]{5,10}$/, message: '密码必须是5-10个字母或数字', trigger: 'blur' }
      ]
    }
    const loginFormRef = ref<FormInstance>()

    const dealLoginClicked = (isKeepPassword: boolean) => {
      loginFormRef.value?.validate((valid) => {
        if (valid) {
          if (isKeepPassword) {
            setStorage.setCatch('name', loginForm.name)
            setStorage.setCatch('password', loginForm.password)
          } else {
            setStorage.deleteCatch('name')
            setStorage.deleteCatch('password')
          }
          store.dispatch('login/getTokenAction', { ...loginForm })
        }
      })
    }
    return {
      loginForm,
      loginRules,
      loginFormRef,
      dealLoginClicked
    }
  }
})
</script>

<style scoped></style>
